/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package net.hnilica.cisteniulic.servlet;

import com.google.code.kaptcha.Producer;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.google.code.kaptcha.servlet.KaptchaServlet;
import com.google.code.kaptcha.util.Config;
import java.awt.image.BufferedImage;
import java.util.Enumeration;
import java.util.Properties;
import javax.imageio.ImageIO;
import javax.servlet.ServletConfig;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpSession;

/**
 * There is a small logic wrong. If someone click on kaptcha image after first successful
 * input of kaptcha. So he changes kaptcha for request but does not change for kaptcha saved in session
 * (after successful input of kaptcha, it saves to session). But no clever man will change successful
 * inputed kaptcha.
 *
 *
 * @author swosh
 */
public class KaptchaServletMy extends HttpServlet {

    private Properties props = new Properties();
    private Producer kaptchaProducer = null;
    private String sessionKeyValue = null;

    /*
     * (non-Javadoc)
     *
     * @see javax.servlet.Servlet#init(javax.servlet.ServletConfig)
     */
    public void init(ServletConfig conf) throws ServletException {
        super.init(conf);

        // Switch off disk based caching.
        ImageIO.setUseCache(false);

        Enumeration<?> initParams = conf.getInitParameterNames();
        while (initParams.hasMoreElements()) {
            String key = (String) initParams.nextElement();
            String value = conf.getInitParameter(key);
            props.put(key, value);
        }

        Config config = new Config(props);
        this.kaptchaProducer = (Producer) config.getProducerImpl();
        this.sessionKeyValue = config.getSessionKey();
    }

    /** */
    public void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        // Set to expire far in the past.
        resp.setDateHeader("Expires", 0);
        // Set standard HTTP/1.1 no-cache headers.
        resp.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
        // Set IE extended HTTP/1.1 no-cache headers (use addHeader).
        resp.addHeader("Cache-Control", "post-check=0, pre-check=0");
        // Set standard HTTP/1.0 no-cache header.
        resp.setHeader("Pragma", "no-cache");

        // return a jpeg
        resp.setContentType("image/jpeg");


        // MY EDIT This block causes u cant write kaptcha againts if u hava written it right before
        String noMakeNewkaptcha;
        String capText = "";
        HttpSession session = req.getSession(true);
        try {
            noMakeNewkaptcha = (String) session.getAttribute("noMakeNewKaptcha");
        } catch (NullPointerException e) {
            noMakeNewkaptcha = "false";
        }
        boolean noMakeNewKaptchaB = Boolean.parseBoolean(noMakeNewkaptcha);


        try {
            capText = (noMakeNewKaptchaB) ? session.getAttribute("kaptchaKey").toString()
                    : kaptchaProducer.createText();
        } catch (NullPointerException e) {
            kaptchaProducer.createText();
        }
        //If something was badly done....so capText cant stay empty
        if (capText.equals("")) {
            kaptchaProducer.createText();
        }
        // create the text for the image
        // THIS WAS CHANGED capText = kaptchaProducer.createText();



        // store the text in the session
        req.getSession().setAttribute(this.sessionKeyValue, capText);

        // create the image with the text
        BufferedImage bi = kaptchaProducer.createImage(capText);

        ServletOutputStream out = resp.getOutputStream();

        // write the data out
        ImageIO.write(bi, "jpg", out);
        try {
            out.flush();
        } finally {
            out.close();
        }
    }

}
